﻿using ShareRss.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using HtmlAgilityPack;
using System.Threading.Tasks;

namespace ShareRss.Dll
{
    public class HtmlToXpath
    {
        /// <summary>
        /// 获取页面的所有HTML
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string WebParities(string url)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Timeout = 30000;
            HttpWebResponse myWebResponse = webRequest.GetResponse() as HttpWebResponse;
            Stream st = myWebResponse.GetResponseStream();
            if (myWebResponse.ContentEncoding.ToLower().Contains("gzip"))
            {
                st = new GZipStream(st, CompressionMode.Decompress);
            }
            using (StreamReader sr = new StreamReader(st, Encoding.UTF8))
            {
                string Temp = sr.ReadToEnd();
                st.Close();//关闭资源
                myWebResponse.Close();
                webRequest.Abort();//释放
                return Temp;
            }
        }

        /// <summary>
        /// 放入网址，返回地址model
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static MagnetLink HtmlToLink(string html)
        {
            //html = TxtIO.Read("123456", "LoveList");
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            html = doc.DocumentNode.SelectSingleNode("//div[@class='topic-main']/div[@id='resource-tabs']/div[@id='tabs-1']").InnerHtml.Trim() + "</p>";
            doc.LoadHtml(html);
            MagnetLink mg = new MagnetLink()
            {
                VipLink = doc.DocumentNode.SelectNodes("/p/a")[0].Attributes["href"].Value,
                Magnet = doc.DocumentNode.SelectNodes("/p/p[1]/a")[0].Attributes["href"].Value,
                Magnet2 = doc.DocumentNode.SelectNodes("/p/p[2]/a")[0].Attributes["href"].Value
            };
            return mg;
        }
    }
}
